import React, { useState, useEffect, useContext } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Form, Input, Button, DatePicker, Select, message, Card, Divider } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import moment from 'moment';
import { projectApi, projectVersionApi } from '../services/api';
import Header from '../components/layout/Header';
import { useKeycloak } from '../contexts/KeycloakContext';

const { Option } = Select;
const { TextArea } = Input;

const AddVersionPage = () => {
  const { projectId } = useParams();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [project, setProject] = useState(null);
  const [darkMode, setDarkMode] = useState(false); // 如果需要主题切换，可以替换为 useTheme hook
  const { user } = useKeycloak(); // 获取当前登录用户信息

  // 获取项目信息
  useEffect(() => {
    const fetchProjectDetails = async () => {
      try {
        if (projectId) {
          const response = await projectApi.getProject(projectId);
          if (response && response.code === 200) {
            setProject(response.data);
          } else {
            message.error('获取项目信息失败: ' + (response?.message || '未知错误'));
          }
        }
      } catch (error) {
        console.error('获取项目信息失败:', error);
        message.error('获取项目信息失败: ' + (error.message || '未知错误'));
      }
    };

    fetchProjectDetails();
  }, [projectId]);

  // 提交表单
  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      // 格式化日期
      const formattedValues = {
        ...values,
        projectId: projectId,
        userId: user?.id, // 添加当前用户ID
        releaseDate: values.releaseDate ? values.releaseDate.format('YYYY-MM-DD') : null,
        changes: values.changes ? values.changes.split('\n').filter(item => item.trim() !== '') : []
      };

      console.log('提交版本数据:', formattedValues);

      // 发送请求
      const response = await projectVersionApi.addProjectVersion(formattedValues);
      
      if (response && (response.code === 200 || response.code === '200')) {
        message.success('版本创建成功');
        // 跳转到版本列表页面
        navigate(`/project/${projectId}/versions`);
      } else {
        message.error(response?.message || '创建失败，请重试');
      }
    } catch (error) {
      console.error('创建版本失败:', error);
      message.error('创建失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  // 返回项目详情页
  const goBack = () => {
    navigate('/projects');
  };

  return (
    <div style={{ 
      flex: 1,
      padding: '16px 24px 24px',
      backgroundColor: '#fff',
      overflow: 'auto',
      boxSizing: 'border-box',
      marginLeft: '200px', // 侧边栏宽度
      marginTop: '64px', // 顶部导航栏高度
      height: 'calc(100vh - 64px)' // 视口高度减去顶部导航栏
    }}>
      <div style={{ 
        maxWidth: '1200px', 
        margin: '0 auto',
        display: 'flex',
        flexDirection: 'column',
        height: '100%'
      }}>
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          marginBottom: '16px',
          paddingBottom: '16px',
          borderBottom: '1px solid #f0f0f0'
        }}>
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={goBack}
            style={{ marginRight: '16px' }}
          >
            返回
          </Button>
          <h2 style={{ margin: 0 }}>新增版本</h2>
        </div>
        
        {project && (
          <div style={{ 
            marginBottom: '24px',
            padding: '12px 16px',
            backgroundColor: '#fafafa',
            borderRadius: '4px',
            border: '1px solid #f0f0f0'
          }}>
            <h3 style={{ margin: '0 0 8px 0' }}>项目：{project.name}</h3>
            <p style={{ margin: 0, color: '#666' }}>当前版本: {project.latestVersion || '无'}</p>
          </div>
        )}
        
        <Card 
          style={{ 
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            boxShadow: 'none',
            border: '1px solid #f0f0f0',
            borderRadius: '4px',
            overflow: 'hidden'
          }}
          bodyStyle={{ 
            flex: 1, 
            padding: '24px',
            display: 'flex',
            flexDirection: 'column' 
          }}
        >

          
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              versionType: 'feature',
              status: 'stable'
            }}
          >
            <Form.Item
              name="versionNumber"
              label="版本号"
              rules={[{ required: true, message: '请输入版本号' }]}
            >
              <Input placeholder="例如: 1.0.0" />
            </Form.Item>
            <Form.Item
              name="status"
              label="版本状态"
              rules={[{ required: true, message: '请选择版本状态' }]}
            >
              <Select>
                <Option value="stable">生产版本</Option>
                <Option value="beta">测试版本</Option>
                <Option value="alpha">内测版本</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="changes"
              label="更新内容"
              rules={[{ required: true, message: '请输入更新内容' }]}
            >
              <TextArea 
                rows={6} 
                placeholder="请输入更新内容，每行一条，例如:&#10;1. 新增用户管理功能&#10;2. 修复登录页面bug&#10;3. 优化页面加载速度" 
              />
            </Form.Item>
            
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading} block>
                提交
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default AddVersionPage;
